package com.white.androidhistoryechoes.view.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.white.androidhistoryechoes.databinding.ItemHistoryEchoesBinding
import com.white.androidhistoryechoes.model.HistoryEchoes

class HistoryEchoesAdapter : RecyclerView.Adapter<HistoryEchoesAdapter.ViewHolder>() {
    var mData: List<HistoryEchoes.Data> = mutableListOf()
        set(value) {
            field = value
            notifyDataSetChanged()
        }
    private var mOnItemHistoryEchosClickListener: (view: View, model: HistoryEchoes.Data) -> Unit =
        { _, _ -> }

    fun setOnItemHistoryEchosClickListener(onItemHistoryEchosClickListener: (view: View, model: HistoryEchoes.Data) -> Unit) {
        mOnItemHistoryEchosClickListener = onItemHistoryEchosClickListener
    }

    inner class ViewHolder(val binding: ItemHistoryEchoesBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bindData(model: HistoryEchoes.Data) {
            binding.tvYear.text = model.year.toString()
            binding.tvTitle.text = model.title
            binding.root.setOnClickListener{
                mOnItemHistoryEchosClickListener.invoke(it, model)
            }
        }

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ItemHistoryEchoesBinding.inflate(
            LayoutInflater.from(parent.context),
            parent, false
        )
        return ViewHolder(binding)

    }

    override fun getItemCount() = mData.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val model = mData[position]
        holder.bindData(model)
    }
}